#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>

#define SHMKEY 33

typedef struct {
  char file[10][60]; 
  int n;
} Pile;

void impression(char *nomFic){
  printf("Debut d'impression de \"%s\"...\n", nomFic);
  sleep(5); /* Simule la lenteur de l'impression */
  printf("...Fin d'impression de \"%s\"...\n", nomFic);

}

int main(){
  int m;
  Pile *pile;
  m = shmget(SHMKEY, sizeof(Pile), IPC_CREAT | 0666);
  if (m < 0) {
    perror("shmget");
    return EXIT_FAILURE;
  }
  if ((pile = (Pile *)shmat(m, NULL, 0)) < (Pile *) 0) {
    perror("shmat"); /* Boucle d'attente */
    exit(EXIT_FAILURE);
  }
  pile->n = 0; /* Init */ 
  do {
    sleep(1); /* Check every 1 sec */
    if (pile->n != 0) { /* If there are some elements */
      impression(pile->file[pile->n]);
      pile->n -= 1; /* On dépile */
    }
  } while(1);

  /* Détachement */
  if (shmdt(pile)<0) {
    perror("shmdt");
    return EXIT_FAILURE; 
  } 
  return EXIT_SUCCESS;
}
